<?php
/************************************************************************
 Omnitrix - PHP Development Framework
 Copyright (C) 2012-2018 amonest(eastson@outlook.com)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
************************************************************************/

function otx_plugin_path($plugin_name, $sub_path = null)
{
	$plugin_path = DIR_PLUGINS . $plugin_name . DS;

	if (empty($sub_path)) {
		return $plugin_path;
	} else {
		return $plugin_path . $sub_path;
	}
}

function otx_plugin_instance($plugin_name)
{
	global $_XPLUGINS;
 	static $plugins = array();

	if (array_key_exists($plugin_name, $plugins)) {
		return $plugins[$plugin_name];
	}

	$plugin_path = otx_plugin_path($plugin_name);
	if (!is_dir($plugin_path)) {
		throw new Exception('Plugin directory not exists: ' . $plugin_path);
	}

	$plugin_file = $plugin_path . DS. $plugin_name . '.php';
	if (!is_file($plugin_file)) {
		throw new Exception('Plugin file not exists: ' . $plugin_file);
	}

	require_once $plugin_file;

	$plugin_class = $plugin_name . '_plugin';
	if (!class_exists($plugin_class)) {
		throw new Exception('Plugin class not exists: ' . $plugin_class);
	}

	$instance = new $plugin_class();
	$instance->plugin_name = $plugin_name;
	$instance->plugin_path = $plugin_path;

	if (array_key_exists($plugin_name, $_XPLUGINS)) {
		$instance->plugin_id = $_XPLUGINS[$plugin_name]['plugin_id'];
		$instance->plugin_status = $_XPLUGINS[$plugin_name]['plugin_status'];
	}

	$plugins[$plugin_name] = $instance;
	return $instance;
}

function otx_plugin_info($plugin_name)
{
	if (is_string($plugin_name)) {
		$instance = otx_plugin_instance($plugin_name);
	} else {
		$instance = $plugin_name;
	}

	$info = array(
		'name' => $instance->plugin_name,
		'title' => $instance->plugin_name,
		'description' => null,
		'website' => null,
		'email' => null,
		'author' => null,
		'version' => null
	);

	return array_merge($info, $instance->get_info());
}